<template>
	<view>
		<image src="" style="width: 100%; height: 180upx; z-index: -99;" v-if="share == 0">
			<view class="box-shadow" style="background-image: url(https://tool.tuanhaoke.cn/static/image/recommend/background_top.png);">
				<view class="position">
					<view class="position-mag" @click="location">
						<image :src="imglink + 'recommend/location.svg'" style="width: 50upx;height: 50upx;vertical-align: middle;"></image>
						<view style="display: inline-block; text-align: left; height: 50upx; width: 150upx; overflow: hidden; margin: 0 10upx;vertical-align: middle;color: #FFFFFF;z-index: 1;">{{locaAddress}}</view>
						<image :src="imglink + 'recommend/down.svg'" style="width: 50upx;height: 50upx;vertical-align: middle;" ></image>
					</view>
						<navigator style="display: inline-block;margin-left: 350upx;" url="/pages/recommend/specific/investigation">
							<image :src="imglink + 'recommend/search.png'" class="inves-img"></image>
						</navigator>
				</view>
				<scroll-view scroll-x="true" class="listda">
					<view class="list-f" v-for="(item,index) in subjectlist" :key="index">
						<view class="subject-reversal" :class="{'reversal': item.id == topnum}">
							<view @click="choseForm(item)">
								<view>{{item.name}}</view>
								<view style="" :class="{'subject-bottom' : item.id == topnum}"></view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</image>
		<!-- 有活动 推荐 -->
		<view class="exist-activity" v-if="activities.length != 0 && topnum == 0">
			<scroll-view :class="share == 0 ? 'noshare-activity' : 'share-activity'" scroll-y="true" scroll-with-animation @scrolltolower="getActivies">
				<view class="activity-mag" v-for="(activity,index) in activities" :key='activity.activity_id' @click="enterDetails(activity.activity_id,activity.storeId)">
					<view class="activity-mag-img">
						<image :src="activity.cover_image" mode="aspectFill"></image>
						<text v-if="activity.activity_type!= 0">拼团</text>
						<text v-else>特惠</text>
					</view>
					<view class="course-msg">
						{{activity.title | getStr(22)}}
					</view>
					<view class="join-msg">
						<view class="num-human">
							<view class="">
								{{activity.total_participants}}人已参与，剩余名额<text>{{activity.total_remaining}}</text>个
							</view>
							<view class="botline">
								<!-- 底下的进度条 -->
								<view class="topline" :style="{width:activity.participant_percent + '%'}"></view>
							</view>
						</view>
						<view class="" @click.stop="enterDetails(activity.activity_id,activity.storeId)">
							立即参与
						</view>
					</view>
					<view class="activity-addr" v-if="activity.sale_rooms.length>0">
						<view>活动地区:</view>
						<view>
							<p v-for="(sale_room,index) in activity.sale_rooms" :key='index'>{{ sale_room }} </p>
						</view>
					</view>
					<view class="activity-addr" v-else>

					</view>
				</view>
				<ending ></ending>
			</scroll-view>
		</view>
		<!-- 有活动 科目 -->
		<view class="exist-activity" v-if="activities.length != 0 && topnum != 0">
			<scroll-view :class="share == 0 ? 'noshare-activity' : 'share-activity'" scroll-y="true" scroll-with-animation @scrolltolower="getActivies">
				<view class="activity-mag" v-for="(activity,index) in kemActivities" :key='activity.activity_id' @click="enterDetails(activity.activity_id,activity.storeId)">
					<view class="activity-mag-img">
						<image :src="activity.cover_image" mode="aspectFill"></image>
						<text v-if="activity.activity_type!= 0">拼团</text>
						<text v-else>特惠</text>
					</view>
					<view class="course-msg">
						{{activity.title | getStr(22)}}
					</view>
					<view class="join-msg">
						<view class="num-human">
							<view class="">
								{{activity.total_participants}}人已参与，剩余名额<text>{{activity.total_remaining}}</text>个
							</view>
							<view class="botline">
								<!-- 底下的进度条 -->
								<view class="topline" :style="{width:activity.participant_percent + '%'}"></view>
							</view>
						</view>
						<view class="" @click.stop="enterDetails(activity.activity_id,activity.storeId)">
							立即参与
						</view>
					</view>
					<view class="activity-addr" v-if="activity.sale_rooms.length>0">
						<view>活动地区:</view>
						<view>
							<p v-for="(sale_room,index) in activity.sale_rooms" :key='index'>{{ sale_room }} </p>
						</view>
					</view>
					<view class="activity-addr" v-else>
		
					</view>
				</view>
				<!-- <ending v-if="page > last_page"></ending> -->
				<ending></ending>
			</scroll-view>
		</view>
		<!-- 无活动 -->
		<view :class="share == 0 ? 'no-activity' : 'no-share-activity'" v-if="activities.length == 0">
			<view class="no-activity-tip" v-if="is_current_store_owner == 1">
				你还没有任何活动，请先建立自己运营活动
			</view>
			<view class="no-activity-img">
				<image :src="imglink + 'nothing-activity.png'" mode=""></image>
				<view class="">
					你还没有任何活动哦！
				</view>
			</view>
			<!-- <view class="found-activity" @click="organizationEnter" v-if="is_current_store_owner == 1">
				创建新活动
			</view> -->
		</view>
		<tabBar :storeId='store_id'></tabBar>
	</view>
</template>

<script>
	import ending from '../../common/ending.vue'
	import tabBar from '@/common/tabBar.vue'
	export default {
		filters: {
			getStr(str, new_length) {

				// console.log('getStr', str);
				if (!str) {
					return ''
				}
				if (str.length > new_length) {
					return str.slice(0, new_length) + '...'
				} else {
					return str
				}
			},
		},
		components: {
			ending,
			tabBar
		},
		data() {
			return {
				imglink: this.$store.state.imgLink,
				storeId:'',
				width: [],
				height: 0,
				meta_tag_title: '',
				store_id: 0,
				store_info: {},
				token: '',
				customer_info: {},
				is_current_store_owner: 0,
				activities: [],
				page: 0,
				page_size: 8,
				last_pag: 1,
				current_page: 1,
				windowWidth: 0,
				windowHeight: 0,
				topnum:0,
				subjectlist:[
					{
						id:0,
						source:0,
						name:'推荐'
					},
				],
				subject:[],
				locaAddress:'定位中',
				longitude:'',
				latitude:'',
				kemActivities:[],
				share: 0,
			}
		},
		onLoad(options) {
			
			var that = this
			// #ifdef H5
				this.$store.commit('updataShare', 1)
			// #endif
			const {
				windowWidth,
				windowHeight
			} = uni.getSystemInfoSync();
			that.windowWidth = windowWidth;
			that.windowHeight = windowHeight;
			let store_id = parseInt(options.store_id, 10);
			if (!store_id > 0) {
				store_id = uni.getStorageSync('store_id')
			} else {
				uni.setStorageSync('store_id', store_id)
			}
			that.locaAddress = uni.getStorageSync('locaAddress')
			that.store_id = store_id
			
			let is_extension = uni.getStorageSync('is_extension')
			if(!is_extension){
				that.$store.commit('updateStoreId', store_id)
			}
			
			that.share = that.$store.state.share
			console.log(that.share,"？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？");
			// #ifdef H5
				let pages = getCurrentPages()
				that.currentPge = pages[0].$route.fullPath
			// #endif

			let token = options.token;
			if (!token) {
				token = uni.getStorageSync('token')
			} else {
				uni.setStorageSync('token', token);
			}
			//#ifdef H5
			if (!token) {
				let url = that.$store.state.URL + "/customer/user/wx_login?page=" + encodeURIComponent(that.currentPge)
				location.href = url
				return
			}
			//#endif
			
			that.token = token
			that.$store.commit('updateToken', token)

			that.share_customer_id = options.share_customer_id

			that.height = parseInt(uni.getSystemInfoSync().windowHeight) - that.height

			//  去除分享链接中分享者的token
			const stateObj = that.currentPge
			let pattern = /(&token+.*&)|(&token+.*)/
			// #ifdef H5
				that.currentPge = that.currentPge.replace(pattern, '&')
				history.replaceState(stateObj, "", that.currentPge)
			// #endif
			that.getAllAubjects()
			if(options.type == 2){
				that.locaAddress = decodeURI(options.poiname);
				that.longitude = options.lng;
				that.latitude = options.lat;
				console.log(that.longitude,that.longitude,"++++++++++++++++++++++++++++++++");
				// that.getGeocoders();
			}else{
				wx.getLocation({
					type: 'gcj02',
					isHighAccuracy: true,
					success: function (res) {
						console.log(res)
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						
						that.longitude = res.longitude
						that.latitude = res.latitude
						if( that.locaAddress == '定位中' ){
							that.getGeocoders()
						}
					},
					fail(res) {
						console.log(res,'接口调用失败');
						// uni.showToast({
						// 	title:'定位失败!',
						// 	icon:'none',
						// 	duration:1000,
						// })
					}
				});
			}
		},
		async onShow() {
			// #ifdef MP-WEIXIN
				wx.hideHomeButton()
			// #endif
			// 获取店铺信息
			await this.getStore()
			if (this.store_info.name) {
				uni.setNavigationBarTitle({
					title: this.store_info.name
				})
			}
			// 获取用户信息
			
			await this.getActivies()
			
			// #ifdef MP-WEIXIN
				const chooseLocation = requirePlugin('chooseLocation');
				const location = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
				if( location != '' ){
					this.locaAddress = location.name;
					this.longitude = location.longitude;
					this.latitude = location.latitude;
				}
				console.log(location);
				uni.setStorageSync('locaAddress',this.locaAddress)
			// #endif
		},

		methods: {
			// 逆地址解析
			getGeocoders(){
				let data  = {
					token:this.$store.getters.getToken,
					lat: this.latitude,
					lng: this.longitude
				}
				console.log(data,"++++++++++++++++++++++++");
				this.$api.get_geocoder(data).then(res => {
					console.log(res,"逆地址解析")
					if(res.status){
						this.locaAddress = res.localAddress
						uni.setStorageSync('locaAddress',this.locaAddress)
					}else{
						uni.showToast({
							title:res.msg,
							icon:'none',
							duration:2000
						})
					}
				}).catch(err => {
					console.log(err)
				})
			},
			choseForm(item){
				this.topnum = item.id
				this.kemActivities = []
				this.activities.forEach((data) => {
					if( data.subjects_id == this.topnum ){
						this.kemActivities.push(data)
					}
				})
			},
			// 打开地图
			location(){
				// #ifdef H5
					uni.navigateTo({
						url: 'homeAddress?type=1'
					})
				// #endif
				// #ifdef MP-WEIXIN
					const key = this.$store.state.qqmapkey; //使用在腾讯位置服务申请的key
					const referer = '团好课课拍'; //调用插件的app的名称
					wx.navigateTo({
					  url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer
					});
				// #endif
			},
			// 获取科目
			getAllAubjects(){
				let data  = {
						token:this.$store.getters.getToken,
					}
				this.$api.get_allAubjects(data).then(res => {
					console.log(res)
					if(res.status){
						this.subject = res.data
						console.log(this.subject,'科目');
						let su = this.subjectlist.concat(this.subject)
						this.subjectlist = su
					}else{
						uni.showToast({
							title:res.msg,
							icon:'none',
							duration:2000
						})
					}
				}).catch(err => {
					console.log(err)
				})
			},
			async getStore() {
				try {
					const data = {
						customer_store_id: this.store_id
					}
					this.$api.gain_shop_msg(data).then(res => {
						// console.log(res)
						if (res.status) {
							this.store_info = res.data
							this.$store.commit('updataCustomerId', this.store_info.customer_id);
							uni.setStorageSync('customer_id', this.store_info.customer_id)

						}
					}).catch(err => {
						console.log(err)
					})
					// let store_info = (await this.$api.gain_shop_msg(data)).data
					// this.store_info = store_info

				} catch (e) {
					console.log(e);
				}

			},
			async getCustomer() {
				const data = {
					token: this.token,
					// customer_id:this.store_info.customer_id,
					store_id: this.store_id
				}
				this.$api.getCustomerInfo(data).then(res => {
					console.log(res)
					if (res.status) {
						//获取活动信息
						this.customer_info = res.data
						this.$store.commit('updataUserInfo', this.customer_info.userinfo);
						uni.setStorageSync('userInfo', this.customer_info.userinfo)
						console.log(this.customer_info.userinfo,"454545454545");
						//判断用户是否为店主
						if (this.customer_info.role == 3) {
							this.is_current_store_owner = 1
						}
					}
				}).catch(err => {
					console.log(err)
				})
				// let customer_info = this.$api.getCustomerInfo(data)
				// console.log(this.customer_info)

			},
			async getActivies() {
				this.page = this.page + 1;
				if (this.page > this.last_page) {
					return false
				}
				// #ifdef MP-WEIXIN
					let data = {}
					if( this.share == 0 ){
						data = {
							page: this.page,
							pagesize: this.page_size,
							// store_id: this.store_id,
							exit_type_collectioncode: true
						}
					}else{
						data = {
							page: this.page,
							pagesize: this.page_size,
							store_id: this.store_id,
							exit_type_collectioncode: true
						}
					}
				// #endif
				// #ifdef H5
					let data = {
							page: this.page,
							pagesize: this.page_size,
							store_id: this.store_id,
							exit_type_collectioncode: true
						}
				// #endif
				this.$api.gain_all_act(data).then(res => {
					// console.log(res, 'gain_all_act')
					if (res.status) {
						const activities = []
						console.log(res.list.data,"？？？？？？？？？？？？？？？？？？？？？？？？？");
						res.list.data.forEach(item => {
							if (item.active_status == 1 && item.operate_status == 1) {
								activities.push(item)
							}
						})
						
						this.last_page = res.list.last_page
						console.log(this.last_page, '1111111')
						activities.forEach(item => {

							//活动类型
							let activity_type = 0 //0团购活动
							if (item.group_purchase && item.group_purchase.length > 0) {
								activity_type = 1 //1优惠活动
							}

							//活动封面
							let cover_image = ''
							if (item.image && item.image.length > 0) {
								cover_image = item.image[0].image
							}

							//所有参与门店的地址（排除重复）
							let sale_rooms = []
							if (item.salesroom.length != 0) {

								item.salesroom.forEach(room => {
									sale_rooms.push(room.province_id + '省' + room.city_id + room.country_id + room.address);
								});

							}
							let participant_percent = 0;
							// console.log('item.virtual_total item.participants item.allowed_total', item.virtual_total, item.participants,
								// item.allowed_total);

							if (parseInt(item.allowed_total, 10) > 0) {

								participant_percent = Math.round((item.virtual_total + item.buyer) / item.allowed_total * 10000) /
									100.00
							}
							// console.log('participant_percent', participant_percent);

							this.activities.push({
								activity_id: item.activity_id,
								activity_type,
								cover_image,
								title: item.name,
								total_participants: item.virtual_total + item.buyer,
								total_remaining: (item.allowed_total -  item.buyer - item.virtual_total) > 0 ? (item.allowed_total -  item.buyer - item.virtual_total) : 0,
								sale_rooms,
								participant_percent,
								subjects_id:item.subjects_id,
								storeId:item.store_id
							});
							console.log(this.activities, '1111111111')
						
						})

					} else {

						uni.showToast({
							title: res.msg,
							icon: "none",
							duration: 2000
						})
					}
				}).catch(err => {
					console.log(err)
				})
				await this.getCustomer()
			},
			// enterDetails(activity_id){
			// 	uni.navigateTo({
			// 		url:'organization/activeDetails?page=details&actId='+activity_id + '&store_id=' + this.store_id
			// 	})
			// },
			enterDetails(activity_id,storeId) {
				let data = {
					token:this.$store.getters.getToken,
					store_id:storeId,
					activity_id:activity_id
				}
				console.log(data,"8888888");
				// 3.发送请求
				this.$api.add_activityUser(data).then(res => {
					if(res.status){
						uni.navigateTo({
							url: 'organization/activeDetail-3?page=details&actId=' + activity_id + '&store_id=' + this.store_id
						})
					}else{
						uni.showToast({
							title:res.msg,
							icon:'none',
							duration:2000
						})
					}
				}).catch(err =>{
					console.log(err)
				})
			},
			//#ifdef H5
			organizationEnter() {
				if (this.$store.getters.getToken) {
					uni.navigateTo({
						url: '../memberCenter/activity/createActivity?store_id=' + this.store_id
					})
				} else {
					// console.log('跳转地址',this.$store.state.URL + "customer/user/wx_login?page=pages/memberCenter/activity/createActivity&share_customer_id=1")
					location.href = this.$store.state.URL +
						"customer/user/wx_login?page=pages/memberCenter/activity/createActivity&share_customer_id=" + this.share_customer_id
				}
			},
			//#endif

		}
	}
</script>

<style>
	page {
		background: #F3F3F4;
	}

	.no-share-activity {
		height: 94vh;
		background-color: white;
	}
	.no-activity {
		height: 80vh;
		background-color: white;
	}
	.no-activity-tip {
		width: 100%;
		height: 56upx;
		line-height: 56upx;
		background: #FFF7D8;
		text-align: center;
		color: #666666;
		font-size: 24upx;
	}

	.no-activity-img>image {
		width: 100%;
		height: 286upx;
		margin-top: 208upx;
	}

	.no-activity-img>view {
		color: #999999;
		font-size: 28upx;
		text-align: center;
	}

	.found-activity {
		width: 650upx;
		height: 100upx;
		line-height: 100upx;
		margin: 0 auto;
		text-align: center;
		margin-top: 92upx;
		border-radius: 44upx;
		font-size: 32upx;
		color: white;
		background: linear-gradient(to right, #FE9543, #FF664F);
		box-shadow: 0 8upx 16upx 0 rgba(166, 13, 0, 0.23);
	}

	.activity-mag {
		width: 100%;
		/* height: 708upx; */
		background: #FFFFFF;
		padding: 30upx 30upx 0 30upx;
		box-sizing: border-box;
		margin-bottom: 20upx;
	}

	.exist-activity {
		width: 100%;
		margin-bottom: 80upx;
	}

	.activity-mag-img {
		width: 100%;
		height: 388upx;
		/* background: rgba(0,0,0,0.3); */
		position: relative;
		text-align: center;
	}

	.activity-mag-img>image {
		width: 100%;
		/* max-width: 100%; */
		max-height: 100%;
	}

	.activity-mag-img>text {
		display: inline-block;
		width: 138upx;
		height: 60upx;
		line-height: 60upx;
		background-image: url(https://tool.tuanhaoke.cn/static/image/home/home_image_back.png);
		background-size: 100% 100%;
		font-size: 28upx;
		text-align: center;
		color: #FFFFFF;
		position: absolute;
		top: -4upx;
		left: -16upx;
	}

	.course-msg {
		color: #333333;
		font-size: 34upx;
		margin-top: 20upx;
	}

	.join-msg {
		display: flex;
		justify-content: space-between;
		margin-top: 20upx;
	}

	.num-human>view:first-child {
		color: #999999;
		font-size: 24upx;
	}

	.num-human>view:first-child>text {
		color: #FF391F;
	}

	.botline {
		width: 100%;
		height: 16upx;
		border-radius: 10upx;
		background: #F1F1F2;
		margin-top: 10upx;
		/* opacity: 0.26; */
	}

	.topline {
		background: linear-gradient(to right, #FE9543, #FF664F);
		border-radius: 20upx;
		height: 16upx;
	}

	.join-msg>view:last-child {
		width: 180upx;
		height: 60upx;
		line-height: 60upx;
		text-align: center;
		color: #FFFFFF;
		background: linear-gradient(to right, #FE9543, #FF664F);
		border-radius: 30upx;
		box-shadow: 0 4upx 12upx 0 rgba(255, 95, 63, 0.47);
		font-size: 28upx;
	}

	.activity-addr {
		width: 100%;
		padding: 14upx 0;
		box-sizing: border-box;
		font-size: 24upx;
		border-top: 1upx solid #DEDEDE;
		margin-top: 30upx;
		display: flex;
		justify-content: flex-start;
	}

	.activity-addr>view:first-child {
		color: #666666;
	}

	.activity-addr>view:last-child>p {
		color: #333333;
		text-indent: 10rpx;
		font-weight: 600;
		font-size: 24rpx;
	}
	.box-shadow{
		box-shadow: 0 -20upx 30upx black;
		/* background-image: url(https://tool.tuanhaoke.cn/static/image//recommend/background_top.png); */
		/* background-color: #000000; */
		margin-top: -200upx;
		z-index: 999;
	}
	.position{
		width: 100%;
		display: inline-block;
		vertical-align: middle;
		z-index: 999;
	}
	.position-mag{
		display: inline-block;
		margin: 20upx 0 20upx 20upx;
		font-size: 35upx;
		text-align: center;
		vertical-align: middle;
	}
	.position-input{
		border-radius: 20upx;
		display: inline-block;
		border: 1upx solid #000000;
		width: 400upx;
		margin-left: 80upx;
		margin-top: 10upx;
		vertical-align: middle;
	}
	.listda{
		width: 100%;
		margin-top: 20upx;
		margin-bottom: 20upx;
		display: inline-block;
		vertical-align: middle;
		overflow: hidden;
		white-space: nowrap;
		z-index: 9;
	}
	.list-f{
		margin: 0 30upx 0 30upx;
		display: inline-block;
	}
	.subject-reversal{
		color: rgba(255,255,255,0.7);
		font-size: 34upx;
		margin-right: 30upx;
		text-align: center;
	}
	.inves-img{
		width: 35upx;
		height: 35upx;
		vertical-align: middle;
		margin: 10upx 0 0 0upx;
		background-color: rgba(255,255,255,0.5);
		border-radius: 60upx;
		padding: 10upx;
	}
	.reversal{
		color: #FFFFFF;
		font-size: 40upx;
	}
	.subject-bottom{
		margin-top: 5upx;
		height: 2upx;
		width: 100%;
		background-color: #FFFFFF;
	}
	.noshare-activity{
		height: 80vh;
	}
	.share-activity{
		height: 93vh;
	}
</style>